<template>
  <div style="padding: 0 20px;height: 100%;overflow: auto;">
    <!-- <el-button type="primary" @click="showAddQualityDialog">新建库位</el-button> -->
    <el-form :model="displayQuality" label-width="130px" :rules="qualityRules" ref="displayFormRef"
             label-position="top">
      <el-row>
        <el-col :span="7">
          <el-form-item label="库位名称" prop="storageId" required>
            <el-select v-model="displayQuality.storageId" placeholder="请选择库位" filterable disabled>
              <el-option v-for="device in data.deviceOptions" :key="device.id" :label="device.storageName"
                         :value="device.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7" :offset="1">
          <el-form-item label="良率（%）" prop="yield">
            <el-input-number placeholder="请输入良率" :step="0.0001" step-strictly :max="100" style="width: 100%;"
                             v-model="displayQuality.yield" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--			<el-col :span="24" style="display: flex; justify-content: flex-end;">-->
      <!--				<el-button @click="handleAdd" :icon="Plus" style="width: 108px;margin-bottom: 10px"> 投入物料 </el-button>-->
      <!--				<el-button type="primary" @click="saveQuality" style="width: 108px;">保存</el-button>-->
      <!--			</el-col>-->
      <el-form-item prop="keys">
        <div style="width: 100%; padding-bottom:10px" v-for="(item, index) in displayQuality.intMaterial" :key="index">
          <el-row>
            <el-col :span="7">
              <el-form-item :label="index + 1 + `. 投入物料`">
                <el-select v-model="item.materialId" clearable filterable placeholder="请选择投入物料" disabled>
                  <el-option v-for="option in data.materialOptions" :key="option.id" :label="option.materialName"
                             :value="option.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-form-item  label="投入转化率" required>
                <el-input v-model="item.numPutCompare" placeholder="请输入投入转化率" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="2" :offset="1">
              <el-form-item label="数量">
                {{ item.orderCount }}
              </el-form-item>
            </el-col>
            <el-col :span="2" :offset="1">
              <el-form-item label="单位">
                {{ item.basicUnit }}
              </el-form-item>
            </el-col>
            <el-col :span="2" :offset="1">
              <el-form-item  label="主物料">
                <el-switch v-model="item.status" active-value="1" inactive-value="0" disabled
                           @change="statusChange(index)"></el-switch>
              </el-form-item>
            </el-col>

          </el-row>
        </div>
      </el-form-item>
      <div style="width: 100%; padding-bottom:10px" v-for="(item, index) in displayQuality.outMaterial" :key="index">
        <el-row>
          <el-col :span="7">
            <el-form-item label="产出物料">
              <el-select v-model="item.materialId" clearable disabled filterable placeholder="请选择产出物料">
                <el-option v-for="option in data.materialOptions" :key="option.id" :label="option.materialName"
                           :value="option.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label="产出转化率">
              <el-input v-model="item.numPutCompare" disabled placeholder="请输入产出转化率"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="1">
            <el-form-item label="数量">
              {{ item.orderCount }}
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="1">
            <el-form-item label="单位">
              {{ item.basicUnit }}
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-col :span="21" style="display: flex; justify-content: flex-end;">
      </el-col>
    </el-form>
  </div>
</template>
<script setup>
import axiosInstance from '@/utils/http/api';
import {onMounted, reactive, watch, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {CircleClose, CirclePlus, Delete, Edit, Download, Plus} from '@element-plus/icons-vue';

const data = reactive({
  showQualityDialog: false,
  newQuality: {storageId: '', keys: [{putMaterialId: '', numPutCompare: ''}]},
  deviceOptions: [],
  materialOptions: []
});

const displayQuality = ref({
  keys: [{
    status: '1'
  }]
});
const baseData = ref([]);
const indexParenId = ref();

const qualityFormRef = ref(null);
const displayFormRef = ref(null);
const qualityRules = {
  storageId: [{required: true, message: '请选择库位名称', trigger: 'change'}],
  qualityType: [{required: true, message: '请选择库位类型', trigger: 'change'}],
  keys: {
    validator: (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error('至少添加一项内容'));
      } else {
        for (let item of value) {
          if (!item.putMaterialId || !item.numPutCompare) {
            // callback(new Error('投入物料和投入转化率不能为空'));
            break;
          }
        }
        callback();
      }
    },
    trigger: 'blur'
  },
  outMaterialId: [{required: true, message: '请选择产出物料', trigger: 'change'}],
  numPutCompare: [{required: true, message: '请输入产出转化率', trigger: 'blur'}]
};

const props = defineProps({
  devicesData: Array,
  onSubmit: Function
});
watch(props, (val) => {
  if (val.devicesData) {
    baseData.value = val?.devicesData?.storage;
    indexParenId.value = val.devicesData.index;
    if (baseData?.value?.[0]?.keys) {
      displayQuality.value = baseData?.value?.[0] || {};
    } else {
      displayQuality.value = {...baseData?.value?.[0], keys: [{putMaterialId: '', numPutCompare: ''}]};
    }

    console.log(baseData.value)
    console.log(indexParenId.value)
  }
});

const showAddQualityDialog = () => {
  data.showQualityDialog = true;
  data.newQuality = {storageId: '', keys: [{putMaterialId: '', numPutCompare: ''}]};
};

const getDeviceOptions = async () => {
  try {
    const response = await axiosInstance.post('/api/basedataStorage/getAll', {});
    data.deviceOptions = response.data;
    const res = await axiosInstance.post('/api/basedataMaterial/getAll', {});
    data.materialOptions = res.data;
  } catch (error) {
    console.error('失败:', error);
  }
};

const handleAdd = () => {

  // data.newQuality.keys.push({ putMaterialId: '', numPutCompare: '' });
  displayQuality.value.keys.push({putMaterialId: '', numPutCompare: ''});
};

const handleRemove = (index) => {
  data.newQuality.keys.splice(index, 1);
  displayQuality.value.keys.splice(index, 1);
};

const statusChange = (e) => {
  const list = JSON.parse(JSON.stringify(displayQuality.value.keys));
  if (list[e].status == 1) {
    for (let i = 0; i < list.length; i++) {
      if (i != e) {
        list[i].status = 0;
      }
    }
  }
  displayQuality.value.keys = list;
};

const addQuality = () => {
  qualityFormRef.value.validate((valid) => {
    if (valid) {
      let addData = [];
      const ids = Math.floor(Math.random() * 100);
      addData = [{...data.newQuality, index_id: ids}];
      const storageData = addData.map(i => {
        return {
          numPutCompare: i.numPutCompare,
          outMaterialId: i.outMaterialId,
          storageId: i.storageId,
          keys: i.keys,
          outMaterial: [{
            MaterialId: i.outMaterialId,
            numPutCompare: i.numPutCompare
          }],
          IntMaterial: i.keys.map(item => {
            return {
              MaterialId: item.putMaterialId,
              numPutCompare: item.numPutCompare
            };
          })
        };
      });

      if (props.onSubmit) {
        props.onSubmit(storageData, 'storage', indexParenId.value);
      }
      data.showQualityDialog = false;
      displayQuality.value = storageData[0];
    }
  });
};

const saveQuality = () => {
  displayFormRef.value.validate((valid) => {
    if (valid) {
      if (props.onSubmit) {
        let hasStatus = 0;
        for (const item of displayQuality.value.keys) {
          if (item.status == 1) {
            hasStatus = 1;
          }
        }
        if (hasStatus == 0) {
          ElMessage.error('未选择主物料');
          return false;
        }
        const storageData = [displayQuality.value].map(i => {

          return {
            numPutCompare: i.numPutCompare,
            outMaterialId: i.outMaterialId,
            storageId: i.storageId,
            keys: i.keys,
            yield: i.yield,
            outMaterial: [{
              MaterialId: i.outMaterialId,
              numPutCompare: i.numPutCompare
            }],
            IntMaterial: i.keys.map(item => {
              return {
                MaterialId: item.putMaterialId,
                numPutCompare: item.numPutCompare,
                status: item.status
              };
            })
          };
        });
        props.onSubmit(storageData, 'storage', indexParenId.value);
      }
    }
  });
};

const editQuality = (row) => {
  console.log(row);
  data.newQuality = row;
  data.showQualityDialog = true;
};

const deleteQuality = (row) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const delBaseData = baseData.value.filter(i => i.index_id !== row.index_id);
    if (props.onSubmit) {
      props.onSubmit(delBaseData, 'quality', indexParenId.value);
    }
  }).catch(() => {
  });
};

const replaceItemById = (items, newItem) => {
  const newData = items.map(i => {
    if (i.index_id === newItem.index_id) {
      return {...newItem};
    }
    return i;
  });
  return newData;
};

onMounted(() => {
  getDeviceOptions();
});
</script>
<style scoped>
.el-table {
  margin-top: 20px;
}
</style>
